import logging
from logging.config import dictConfig

import click
import uvicorn
from fastapi import FastAPI

import views
from settings import LOGGING_DICT, configs
dictConfig(LOGGING_DICT)

from scanner import ConScanner
from shared import SharedObject
from middlewares.content_size_limit_asgi import ContentSizeLimitMiddleware


app = FastAPI(title='瑞星引擎SDK在线调用接口', description='瑞星引擎SDK在线调用接口', version='1.0.0')
app.include_router(views.router, prefix='/lame', tags=[''])

app.add_middleware(ContentSizeLimitMiddleware, max_content_size=configs['max_file_size'])  # 限值上传文件的大小

logger = logging.getLogger('lame')


@app.on_event('startup')
def startup():
    scanner = ConScanner(configs['lamedir'], scan_params=configs['scan_params'])
    scanner.run()
    SharedObject.scanner = scanner
    pass


@app.on_event('shutdown')
def shutdown():
    if SharedObject.scanner:
        SharedObject.scanner.close()


@click.command()
@click.option('-wk', '--workers', default=1, help='number of workers')
@click.option('-ht', '--host', default='127.0.0.1', help='host to listen')
@click.option('-p', '--port', default=9977, help='port to listen')
def main(host, port, workers):
    check_scanner()
    logger.info('listening on {}:{}, worker: {}'.format(host, port, workers))
    uvicorn.run('app:app', host=host, port=port, log_level='warning', workers=workers)


def check_scanner():
    logger.info('check lame scanner...')
    scanner = ConScanner(configs['lamedir'], scan_params=configs['scan_params'])
    scanner.run()
    scanner.close()
    pass


if __name__ == '__main__':
    main()
